"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";

interface Wish {
  id: number;
  user_id: number;
  content: string;
  type: "achieved" | "desired";
  created_at: string;
  updated_at: string;
  achieved_at?: string | null;
}

interface MatchResult {
  matchedUserId: number;
  username: string;
  email: string;
  desiredWishes: Wish[];
}

export default function Dashboard() {
  const [user, setUser] = useState<any>(null);
  const router = useRouter();

  const [achieved, setAchieved] = useState<Wish[]>([]);
  const [desired, setDesired] = useState<Wish[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [matchOpenForId, setMatchOpenForId] = useState<number | null>(null);
  const [matchResults, setMatchResults] = useState<MatchResult[]>([]);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editingContent, setEditingContent] = useState("");

  const token = useMemo(() => {
    if (typeof window === "undefined") return null;
    return localStorage.getItem("token");
  }, []);

  useEffect(() => {
    const token = localStorage.getItem("token");
    const userData = localStorage.getItem("user");
    if (!token || !userData) {
      router.push("/login");
      return;
    }
    setUser(JSON.parse(userData));
    // 初始加载
    void refreshAll();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [router]);

  async function refreshAll() {
    await Promise.all([fetchWishes("achieved"), fetchWishes("desired")]);
  }

  async function fetchWishes(type: "achieved" | "desired") {
    try {
      setLoading(true);
      setError(null);
      const params = new URLSearchParams();
      params.set("type", type);
      if (search.trim()) params.set("q", search.trim());
      const res = await fetch(`/api/wishes?${params.toString()}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "请求失败");
      const data: Wish[] = json.data;
      if (type === "achieved") setAchieved(data);
      else setDesired(data);
    } catch (e: any) {
      setError(e.message || "网络错误");
    } finally {
      setLoading(false);
    }
  }

  async function addWish(type: "achieved" | "desired", content: string) {
    if (!content.trim()) return;
    try {
      setLoading(true);
      const res = await fetch("/api/wishes", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
        body: JSON.stringify({ content, type }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "创建失败");
      await refreshAll();
    } catch (e: any) {
      setError(e.message || "网络错误");
    } finally {
      setLoading(false);
    }
  }

  async function removeWish(id: number) {
    try {
      setLoading(true);
      const res = await fetch(`/api/wishes/${id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "删除失败");
      await refreshAll();
    } catch (e: any) {
      setError(e.message || "网络错误");
    } finally {
      setLoading(false);
    }
  }

  async function saveEdit(id: number) {
    try {
      setLoading(true);
      const res = await fetch(`/api/wishes/${id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
        body: JSON.stringify({ content: editingContent }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "更新失败");
      setEditingId(null);
      setEditingContent("");
      await refreshAll();
    } catch (e: any) {
      setError(e.message || "网络错误");
    } finally {
      setLoading(false);
    }
  }

  async function convertToAchieved(id: number) {
    try {
      setLoading(true);
      const res = await fetch(`/api/wishes/${id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
        body: JSON.stringify({ convert: true }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "转换失败");
      await refreshAll();
    } catch (e: any) {
      setError(e.message || "网络错误");
    } finally {
      setLoading(false);
    }
  }

  async function openMatch(wishId: number) {
    try {
      setLoading(true);
      setMatchOpenForId(wishId);
      const res = await fetch(`/api/wishes/match?wishId=${wishId}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "匹配失败");
      setMatchResults(json.data as MatchResult[]);
    } catch (e: any) {
      setError(e.message || "网络错误");
    } finally {
      setLoading(false);
    }
  }

  const [newAchieved, setNewAchieved] = useState("");
  const [newDesired, setNewDesired] = useState("");

  function formatTime(ts?: string | null) {
    if (!ts) return "";
    const d = new Date(ts);
    return `${d.toLocaleDateString()} ${d.toLocaleTimeString()}`;
  }

  const isFirstTime = achieved.length === 0 && desired.length === 0;

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto">
        <div className="mb-6 flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">愿望匹配平台</h1>
            <p className="text-gray-600">你好，{user?.username}（{user?.email}）</p>
          </div>
          <div className="w-full sm:w-80">
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') void refreshAll();
              }}
              placeholder="搜索你的愿望..."
              className="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        {isFirstTime && (
          <div className="mb-6 rounded-lg bg-yellow-50 p-4 text-yellow-800">
            首次登录提示：请先填写你已实现的愿望，再填写想实现的愿望。
          </div>
        )}

        {error && (
          <div className="mb-4 rounded-md bg-red-50 p-4 text-red-700">{error}</div>
        )}

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 已实现的愿望 */}
          <div className="bg-white shadow rounded-lg p-4">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">已实现的愿望</h2>
            <div className="flex gap-2 mb-4">
              <input
                value={newAchieved}
                onChange={(e) => setNewAchieved(e.target.value)}
                placeholder="例如：学会吉他"
                className="flex-1 rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-green-500"
              />
              <button
                onClick={() => {
                  if (newAchieved.trim()) {
                    void addWish("achieved", newAchieved.trim());
                    setNewAchieved("");
                  }
                }}
                className="rounded-md bg-green-600 px-4 py-2 text-white hover:bg-green-700"
                disabled={loading}
              >
                添加
              </button>
            </div>

            <ul className="space-y-3">
              {achieved.map((w) => (
                <li key={w.id} className="rounded-md border border-gray-200 p-3">
                  {editingId === w.id ? (
                    <div className="flex gap-2">
                      <input
                        value={editingContent}
                        onChange={(e) => setEditingContent(e.target.value)}
                        className="flex-1 rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        onClick={() => void saveEdit(w.id)}
                        className="rounded-md bg-blue-600 px-3 py-2 text-white hover:bg-blue-700"
                      >
                        保存
                      </button>
                      <button
                        onClick={() => {
                          setEditingId(null);
                          setEditingContent("");
                        }}
                        className="rounded-md bg-gray-200 px-3 py-2 text-gray-700 hover:bg-gray-300"
                      >
                        取消
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <div className="font-medium text-gray-900">{w.content}</div>
                        <div className="text-sm text-gray-500">创建：{formatTime(w.created_at)}</div>
                      </div>
                      <div className="flex gap-2">
                        <button
                          onClick={() => {
                            setEditingId(w.id);
                            setEditingContent(w.content);
                          }}
                          className="rounded-md bg-blue-600 px-3 py-2 text-white hover:bg-blue-700"
                        >
                          编辑
                        </button>
                        <button
                          onClick={() => void removeWish(w.id)}
                          className="rounded-md bg-red-600 px-3 py-2 text-white hover:bg-red-700"
                        >
                          删除
                        </button>
                      </div>
                    </div>
                  )}
                </li>
              ))}
            </ul>
          </div>

          {/* 想实现的愿望 */}
          <div className="bg-white shadow rounded-lg p-4">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">想实现的愿望</h2>
            <div className="flex gap-2 mb-4">
              <input
                value={newDesired}
                onChange={(e) => setNewDesired(e.target.value)}
                placeholder="例如：跑完半马"
                className="flex-1 rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <button
                onClick={() => {
                  if (newDesired.trim()) {
                    void addWish("desired", newDesired.trim());
                    setNewDesired("");
                  }
                }}
                className="rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
                disabled={loading}
              >
                添加
              </button>
            </div>

            <ul className="space-y-3">
              {desired.map((w) => (
                <li key={w.id} className="rounded-md border border-gray-200 p-3">
                  {editingId === w.id ? (
                    <div className="flex gap-2">
                      <input
                        value={editingContent}
                        onChange={(e) => setEditingContent(e.target.value)}
                        className="flex-1 rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        onClick={() => void saveEdit(w.id)}
                        className="rounded-md bg-blue-600 px-3 py-2 text-white hover:bg-blue-700"
                      >
                        保存
                      </button>
                      <button
                        onClick={() => {
                          setEditingId(null);
                          setEditingContent("");
                        }}
                        className="rounded-md bg-gray-200 px-3 py-2 text-gray-700 hover:bg-gray-300"
                      >
                        取消
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <div className="font-medium text-gray-900">{w.content}</div>
                        <div className="text-sm text-gray-500">创建：{formatTime(w.created_at)}</div>
                      </div>
                      <div className="flex flex-wrap gap-2">
                        <button
                          onClick={() => {
                            setEditingId(w.id);
                            setEditingContent(w.content);
                          }}
                          className="rounded-md bg-blue-600 px-3 py-2 text-white hover:bg-blue-700"
                        >
                          编辑
                        </button>
                        <button
                          onClick={() => void removeWish(w.id)}
                          className="rounded-md bg-red-600 px-3 py-2 text-white hover:bg-red-700"
                        >
                          删除
                        </button>
                        <button
                          onClick={() => void convertToAchieved(w.id)}
                          className="rounded-md bg-green-600 px-3 py-2 text-white hover:bg-green-700"
                        >
                          标记为已实现
                        </button>
                        <button
                          onClick={() => void openMatch(w.id)}
                          className="rounded-md bg-gray-800 px-3 py-2 text-white hover:bg-gray-900"
                        >
                          匹配已实现者
                        </button>
                      </div>
                    </div>
                  )}
                </li>
              ))}
            </ul>
          </div>
        </div>

        {/* 匹配结果抽屉 */}
        {matchOpenForId && (
          <div className="fixed inset-0 z-50 flex">
            <div className="flex-1 bg-black/40" onClick={() => setMatchOpenForId(null)} />
            <div className="w-full sm:w-[480px] h-full bg-white shadow-xl p-4 overflow-y-auto">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold">匹配结果</h3>
                <button
                  onClick={() => setMatchOpenForId(null)}
                  className="rounded-md bg-gray-200 px-3 py-2 text-gray-700 hover:bg-gray-300"
                >
                  关闭
                </button>
              </div>
              {matchResults.length === 0 ? (
                <div className="text-gray-600">暂无匹配到已实现该愿望的用户。</div>
              ) : (
                <div className="space-y-4">
                  {matchResults.map((m) => (
                    <div key={m.matchedUserId} className="rounded-md border border-gray-200 p-3">
                      <div className="mb-2">
                        <div className="font-medium text-gray-900">{m.username}</div>
                        <div className="text-sm text-gray-500">{m.email}</div>
                      </div>
                      <div>
                        <div className="text-sm text-gray-700 mb-1">TA 想实现的愿望：</div>
                        {m.desiredWishes.length === 0 ? (
                          <div className="text-sm text-gray-500">暂无</div>
                        ) : (
                          <ul className="space-y-1">
                            {m.desiredWishes.map((dw) => (
                              <li key={dw.id} className="rounded bg-gray-50 px-2 py-1 text-sm text-gray-800">
                                {dw.content}（创建：{formatTime(dw.created_at)}）
                              </li>
                            ))}
                          </ul>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}